package com.me.safebox.ui.curl;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;

import net.tsz.afinal.bitmap.core.BitmapDecoder;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.me.safebox.R;
import com.me.safebox.data.SafeFile;
import com.me.safebox.utils.EncryptWorker;

/**
 * 
 * @ClassName: CurlActivity
 * @Description:卷页效果主activity
 * @author: Matrix
 * @date: 2012-12-5 上午10:16:43
 * 
 */
public class CurlActivity extends Activity {

	private int extractBitmapType = 0;// 根据文件路径获得bitmap ；1根据文件流解密获得bitmap

	public static final int EXTRACT_BY_URL = 0;

	public static final int EXTRACT_BY_DECRYPT_DATA = 1;

	public static final String EXTRACT_FOLDERNAME = "foldername";
	private CurlView mCurlView;// 卷页效果视图

	private TextView mTitleTextView;
	private TextView mInfoTextView;
	private TextUtil mTextUtil;

	private Object[] mBitmapIds = null;

	private ArrayList<Parcelable> safeFiles = null;

	private long currentIndex = 0;
	private final int MSG_TITLE_CHANGE = 1;
	private String foldername = "";
	private static float densityDpi=160;
	private static float density=1;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		RelativeLayout layout = (RelativeLayout) LayoutInflater.from(this).inflate(R.layout.layout_curl, null);
		layout.setBackgroundResource(R.drawable.bg_mediascan);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(layout);

		densityDpi=getResources().getDisplayMetrics().densityDpi;
		density=getResources().getDisplayMetrics().density;
		int index = 0;
		if (getLastNonConfigurationInstance() != null) {
			index = (Integer) getLastNonConfigurationInstance();
		}
		mCurlView = (CurlView) findViewById(R.id.curl);
		mCurlView.setBackgroundColor(0xffffffff);//设置相册背景颜色为白色
		mCurlView.setBitmapProvider(new BitmapProvider());
		mCurlView.setSizeChangedObserver(new SizeChangedObserver());
		mCurlView.setPageIndexChangedObserver(new PageIndexChangedObserver());
		mTitleTextView = (TextView) findViewById(R.id.titleView);
		mInfoTextView = (TextView) findViewById(R.id.infoView);
		// mCurlView.setBackgroundResource(R.drawable.bg_mediascan);

		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		extractBitmapType = intent.getIntExtra("extractType", 0);
		switch (extractBitmapType) {
		case EXTRACT_BY_URL:
			mBitmapIds = (Object[]) extras.get("files");
			break;
		case EXTRACT_BY_DECRYPT_DATA:
			safeFiles = extras.getParcelableArrayList("files");
		}
		foldername = intent.getStringExtra(EXTRACT_FOLDERNAME);

		currentIndex = intent.getIntExtra("currentIndex", 0);// changed by
																// shirley
																// 2012-12-27
																// 从long型变为int型
		mCurlView.setCurrentIndex((int) currentIndex);
		Log.i("curl", "activity onCreate currentIndex=" + currentIndex);
		// This is something somewhat experimental. Before uncommenting next
		// line, please see method comments in CurlView.
		// mCurlView.setEnableTouchPressure(true);

	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_TITLE_CHANGE:// title 内容更改
				int currentid = msg.arg1;
				int imgSize = getImageArraySize();
				mTitleTextView.setText(foldername + " " + (currentid + 1) + "/" + imgSize);
				// 如果是最后一张，可以写上*最后一张啦*
				if (currentid + 1 == imgSize) {
					mInfoTextView.setText("*最后一张啦*");
				} else {
					mInfoTextView.setText("左右滑动翻页");
				}
				break;
			}
		}
	};

	@Override
	public void onPause() {
		super.onPause();
		mCurlView.onPause();
	}

	@Override
	public void onResume() {
		super.onResume();
		mCurlView.onResume();
	}

	@Override
	public Object onRetainNonConfigurationInstance() {
		return mCurlView.getCurrentIndex();
	}

	/**
	 * Bitmap provider.
	 */
	private class BitmapProvider implements CurlView.BitmapProvider {

		@Override
		public Bitmap getBitmap(int width, int height, int index) {

			Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
			Canvas c = new Canvas(b);
			// Drawable d = getResources().getDrawable(mBitmapIds[index]);
			Drawable d = null;

			// 绘制背景图片add by shirley 2012-12-27
			Bitmap back = BitmapFactory.decodeResource(getApplicationContext().getResources(), R.drawable.book_back1);

			c.drawBitmap(back, new Rect(0, 0, back.getWidth(), back.getHeight()), new Rect(0, 0, b.getWidth(), b.getHeight()), new Paint());
			back.recycle();
			back = null;

			// --加载图片

			switch (extractBitmapType) {
			case EXTRACT_BY_URL:
				d = new BitmapDrawable(BitmapDecoder.decodeSampledBitmapFromFile(((File) mBitmapIds[index]).getAbsolutePath(), width, height));
				//d = Drawable.createFromPath(((File) mBitmapIds[index]).getAbsolutePath());
				break;
			case EXTRACT_BY_DECRYPT_DATA:
				SafeFile file = (SafeFile) safeFiles.get(index);
				byte[] data = EncryptWorker.decryptFile(file.encrptFilePath);

				d = new BitmapDrawable(BitmapDecoder.decodeSampledBitmapFromData(data, width, height));
			}

			// 如果当前图片损坏，那么显示一张损坏图片
			if (d == null) {
				return BitmapDecoder.decodeSampledBitmapFromResource(getResources(), R.drawable.unvaliable_image, width, height);
			}

			int margin = 2;
			int border = 1;
			Rect r = new Rect(margin, margin, width - margin, height - margin);

			int imageWidth = r.width() - (border * 2);
			int imageHeight = imageWidth * d.getIntrinsicHeight() / d.getIntrinsicWidth();
			if (imageHeight > r.height() - (border * 2)) {
				imageHeight = r.height() - (border * 2);
				imageWidth = imageHeight * d.getIntrinsicWidth() / d.getIntrinsicHeight();
			}

			//进行屏幕和适配性缩放-较小的图片，放大点显示
			int imgIntriWidth=d.getIntrinsicWidth();
			int imgIntriHeight=d.getIntrinsicHeight();
			int screenWdip=px2dip(imageWidth);
			int screenHdip=px2dip(imageHeight);
			float scall=density;
			Log.i("curl", "imageWidth="+imageWidth+",imageHeight="+imageHeight+",screenWdip="+screenWdip+",screenHdip="+screenHdip+",imgIntriWidth="+imgIntriWidth+",imgIntriHeight="+imgIntriHeight);
			if(screenWdip>imgIntriWidth*scall&&screenHdip>imgIntriHeight*scall){
				imageWidth=dip2px(imgIntriWidth*scall);
				imageHeight=dip2px(imgIntriHeight*scall);
			}
			Log.i("curl",  "imageWidth="+imageWidth+",imageHeight="+imageHeight);
			//
			r.left += ((r.width() - imageWidth) / 2) - border;
			r.right = r.left + imageWidth + border + border;
			r.top += ((r.height() - imageHeight) / 2) - border;
			r.bottom = r.top + imageHeight + border + border;

			// 画图片外面的线
			Paint p = new Paint();
			p.setColor(0xFFC0C0C0);
			c.drawRect(r, p);

			r.left += border;
			r.right -= border;
			r.top += border;
			r.bottom -= border;

			d.setBounds(r);
			d.draw(c);

			// 清空图片（这样子是否算是清空了？）add by shirley 2012-12-27
			d = null;
			return b;
		}

		@Override
		public int getBitmapCount() {
			switch (extractBitmapType) {
			case EXTRACT_BY_URL:
				return mBitmapIds.length;
			case EXTRACT_BY_DECRYPT_DATA:
				return safeFiles.size();
			}
			return 0;
		}
	}

	/**
	 * CurlView size changed observer.
	 */
	private class SizeChangedObserver implements CurlView.SizeChangedObserver {
		@Override
		public void onSizeChanged(int w, int h) {
			if (w > h) {
				mCurlView.setViewMode(CurlView.SHOW_TWO_PAGES);
				mCurlView.setMargins(.0f, .0f, .0f, .0f);//双页的时候也没有边距
			} else {
				mCurlView.setViewMode(CurlView.SHOW_ONE_PAGE);
				mCurlView.setMargins(.0f, .0f, .0f, .0f);
			}
		}
	}

	private class PageIndexChangedObserver implements CurlView.PageIndexChangedObserver {

		@Override
		public void onPageChanged(int currentIndex) {
			// TODO Auto-generated method stub
			// -发送图片信息到title
			Message msg = new Message();
			msg.what = MSG_TITLE_CHANGE;
			msg.arg1 = currentIndex;
			mHandler.sendMessage(msg);
		}

	}

	public int getImageArraySize() {
		switch (extractBitmapType) {
		case EXTRACT_BY_URL:
			return mBitmapIds.length;
		case EXTRACT_BY_DECRYPT_DATA:
			return safeFiles.size();
		}
		return 0;
	}

	public String getImageFilename(int index) {
		switch (extractBitmapType) {
		case EXTRACT_BY_URL:
			return ((File) mBitmapIds[index]).getAbsolutePath();
		case EXTRACT_BY_DECRYPT_DATA:
			SafeFile file = (SafeFile) safeFiles.get(index);
			return file.sourceDir;
		}
		return "";
	}
	
	public static int dip2px(float dipValue){                 
//		final float scale = context.getResources().getDisplayMetrics().density;   
//		Log.i("curl", "dip2px  scale="+scale);
//		return (int)(dipValue * scale + 0.5f);   
		return (int)(dipValue* (densityDpi/160));

		}             
	public static int px2dip(float pxValue){                 
//		final float scale = context.getResources().getDisplayMetrics().density;     
//		Log.i("curl", "px2dip  scale="+scale);
//		return (int)(pxValue / scale + 0.5f); 
		
		return (int)((pxValue*160)/densityDpi);

		} 
}